<?php
/**
 * 小程序订阅消息设置API
 * 提供用户订阅消息开关的查询和设置功能
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

// 数据库配置
$dbConfig = [
    'host' => 'localhost',
    'name' => 'nzy_congqian_cn', 
    'user' => 'nzy_congqian_cn',
    'pass' => 'FsnXrDfDhm4wFJSX',
    'charset' => 'utf8mb4'
];

// 数据库连接
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    jsonResponse([
        'success' => false,
        'message' => '数据库连接失败: ' . $e->getMessage()
    ]);
}

// 响应函数
function jsonResponse($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function success($data = null, $message = '操作成功') {
    jsonResponse([
        'code' => 200,
        'success' => true,
        'message' => $message,
        'data' => $data,
        'timestamp' => time()
    ]);
}

function error($message = '操作失败', $code = 400) {
    jsonResponse([
        'code' => $code,
        'success' => false,
        'message' => $message,
        'data' => null,
        'timestamp' => time()
    ]);
}

// 验证微信用户token
function verifyWxToken($token) {
    global $pdo;
    
    if (empty($token)) {
        return null;
    }
    
    try {
        // 从token中获取用户信息
        $sql = "SELECT * FROM users WHERE (openid = ? OR token = ?) AND token_expires > NOW() AND status = 'active'";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$token, $token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        return $user;
    } catch (Exception $e) {
        return null;
    }
}

// 获取用户token
function getUserToken() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (strpos($authHeader, 'Bearer ') === 0) {
        return substr($authHeader, 7);
    }
    
    return $_GET['token'] ?? $_POST['token'] ?? $_GET['openid'] ?? $_POST['openid'] ?? '';
}

// 验证用户身份
$token = getUserToken();
$user = verifyWxToken($token);

if (!$user) {
    error('用户身份验证失败，请重新登录', 401);
}

// 获取用户订阅消息设置
function getUserSubscribeSettings() {
    global $pdo, $user;
    
    try {
        // 获取用户基本信息和订阅设置
        $sql = "SELECT 
                    id,
                    openid,
                    nickname,
                    subscribe_message,
                    created_at,
                    updated_at
                FROM users 
                WHERE id = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$user['id']]);
        $userInfo = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$userInfo) {
            error('用户信息不存在', 404);
        }
        
        // 获取可用的订阅消息模板
        $templateSql = "SELECT 
                          template_key,
                          template_name,
                          template_type,
                          description,
                          is_active
                        FROM subscribe_message_templates 
                        WHERE is_active = 1 
                        ORDER BY template_type, created_at";
        
        $templateStmt = $pdo->query($templateSql);
        $templates = $templateStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 按类型分组模板
        $templatesByType = [];
        foreach ($templates as $template) {
            $type = $template['template_type'];
            if (!isset($templatesByType[$type])) {
                $templatesByType[$type] = [];
            }
            $templatesByType[$type][] = $template;
        }
        
        // 获取用户的消息发送统计
        $statsSql = "SELECT 
                       COUNT(*) as total_sent,
                       COUNT(CASE WHEN JSON_EXTRACT(send_result, '$.success') = true THEN 1 END) as success_count,
                       COUNT(CASE WHEN JSON_EXTRACT(send_result, '$.success') = false THEN 1 END) as failed_count,
                       MAX(created_at) as last_sent_at
                     FROM subscribe_message_logs 
                     WHERE openid = ?";
        
        $statsStmt = $pdo->prepare($statsSql);
        $statsStmt->execute([$user['openid']]);
        $messageStats = $statsStmt->fetch(PDO::FETCH_ASSOC);
        
        success([
            'user_info' => [
                'id' => intval($userInfo['id']),
                'nickname' => $userInfo['nickname'],
                'subscribe_enabled' => intval($userInfo['subscribe_message']) === 1,
                'updated_at' => $userInfo['updated_at']
            ],
            'available_templates' => $templatesByType,
            'message_stats' => [
                'total_sent' => intval($messageStats['total_sent']),
                'success_count' => intval($messageStats['success_count']),
                'failed_count' => intval($messageStats['failed_count']),
                'last_sent_at' => $messageStats['last_sent_at']
            ],
            'template_types' => [
                'reservation' => '预约相关',
                'team_reservation' => '团队预约',
                'volunteer' => '志愿者相关',
                'activity' => '活动相关',
                'system' => '系统通知'
            ]
        ]);
        
    } catch (Exception $e) {
        error('获取订阅设置失败: ' . $e->getMessage(), 500);
    }
}

// 更新用户订阅消息设置
function updateSubscribeSettings() {
    global $pdo, $user;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['subscribe_enabled'])) {
        error('缺少必填参数: subscribe_enabled');
    }
    
    $subscribeEnabled = $input['subscribe_enabled'] ? 1 : 0;
    
    try {
        $pdo->beginTransaction();
        
        // 更新用户订阅设置
        $sql = "UPDATE users 
                SET subscribe_message = ?, 
                    updated_at = NOW() 
                WHERE id = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$subscribeEnabled, $user['id']]);
        
        // 记录操作日志
        if (function_exists('logUserOperation')) {
            logUserOperation($user['id'], 'update_subscribe_settings', [
                'old_value' => $user['subscribe_message'],
                'new_value' => $subscribeEnabled,
                'action' => $subscribeEnabled ? 'enable' : 'disable'
            ]);
        }
        
        $pdo->commit();
        
        $statusText = $subscribeEnabled ? '已开启' : '已关闭';
        success([
            'subscribe_enabled' => $subscribeEnabled === 1,
            'status_text' => $statusText,
            'updated_at' => date('Y-m-d H:i:s')
        ], "订阅消息设置{$statusText}");
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error('更新订阅设置失败: ' . $e->getMessage(), 500);
    }
}

// 获取用户订阅消息历史
function getSubscribeMessageHistory() {
    global $pdo, $user;
    
    $page = max(1, intval($_GET['page'] ?? 1));
    $limit = min(50, max(5, intval($_GET['limit'] ?? 10)));
    $offset = ($page - 1) * $limit;
    
    try {
        // 获取消息发送历史
        $sql = "SELECT 
                    sml.id,
                    sml.template_id,
                    smt.template_name,
                    smt.template_type,
                    JSON_EXTRACT(sml.send_result, '$.success') as is_success,
                    JSON_EXTRACT(sml.send_result, '$.error_message') as error_message,
                    sml.created_at as sent_at,
                    sml.message_data
                FROM subscribe_message_logs sml
                LEFT JOIN subscribe_message_templates smt ON sml.template_id = smt.template_key
                WHERE sml.openid = ?
                ORDER BY sml.created_at DESC
                LIMIT ? OFFSET ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$user['openid'], $limit, $offset]);
        $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 获取总数
        $countSql = "SELECT COUNT(*) FROM subscribe_message_logs WHERE openid = ?";
        $countStmt = $pdo->prepare($countSql);
        $countStmt->execute([$user['openid']]);
        $total = $countStmt->fetchColumn();
        
        // 格式化数据
        foreach ($messages as &$message) {
            $message['id'] = intval($message['id']);
            $message['message_data'] = $message['message_data'] ? json_decode($message['message_data'], true) : null;
            $message['is_success'] = intval($message['is_success']) === 1;
            $message['status'] = $message['is_success'] ? 'success' : 'failed';
            $message['status_text'] = $message['is_success'] ? '发送成功' : '发送失败';
            $message['error_message'] = $message['error_message'] ? trim($message['error_message'], '"') : null;
            $message['sent_at'] = $message['sent_at'];
        }
        
        success([
            'list' => $messages,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => intval($total),
                'pages' => ceil($total / $limit)
            ]
        ]);
        
    } catch (Exception $e) {
        error('获取消息历史失败: ' . $e->getMessage(), 500);
    }
}

// 处理请求
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'settings':
                    getUserSubscribeSettings();
                    break;
                case 'history':
                    getSubscribeMessageHistory();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'POST':
            switch ($action) {
                case 'update':
                    updateSubscribeSettings();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        default:
            error('不支持的请求方法');
    }
    
} catch (PDOException $e) {
    error('数据库错误: ' . $e->getMessage(), 500);
} catch (Exception $e) {
    error('服务器错误: ' . $e->getMessage(), 500);
}
?>